/*
 * @Author: andarm andarm@foxmail.com
 * @Date: 2023-07-23 23:16:06
 * @LastEditors: andarm andarm@foxmail.com
 * @LastEditTime: 2023-07-23 23:16:33
 * @FilePath: \develop_library\c_lib\test\test_openssl.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>

#define AES_BLOCK_SIZE 16

void encrypt(const unsigned char *plaintext, const unsigned char *key, const unsigned char *iv, unsigned char *ciphertext, int length)
{
    AES_KEY aes_key;
    AES_set_encrypt_key(key, 128, &aes_key);
    AES_cbc_encrypt(plaintext, ciphertext, length, &aes_key, iv, AES_ENCRYPT);
}

void decrypt(const unsigned char *ciphertext, const unsigned char *key, const unsigned char *iv, unsigned char *plaintext, int length)
{
    AES_KEY aes_key;
    AES_set_decrypt_key(key, 128, &aes_key);
    AES_cbc_encrypt(ciphertext, plaintext, length, &aes_key, iv, AES_DECRYPT);
}

int main()
{
    unsigned char plaintext[] = "Hello, World!";
    unsigned char key[AES_BLOCK_SIZE] = "0123456789abcdef";
    unsigned char iv[AES_BLOCK_SIZE] = "1234567890abcdef";
    int plaintext_len = strlen((char *)plaintext);

    // 加密
    int ciphertext_len = ((plaintext_len + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
    unsigned char *ciphertext = malloc(ciphertext_len);
    encrypt(plaintext, key, iv, ciphertext, plaintext_len);

    printf("Ciphertext: ");
    for (int i = 0; i < ciphertext_len; i++)
    {
        printf("%02x ", ciphertext[i]);
    }
    printf("\n");

    // 解密
    unsigned char *decryptedtext = malloc(ciphertext_len);
    decrypt(ciphertext, key, iv, decryptedtext, ciphertext_len);

    decryptedtext[plaintext_len] = '\0';
    printf("Decrypted text: %s\n", decryptedtext);

    free(ciphertext);
    free(decryptedtext);

    return 0;
}

// 注意：上述示例中使用了OpenSSL库的AES模块进行加密和解密。在编译时需要链接OpenSSL库，例如使用以下命令进行编译：gcc example.c -o example -lcrypto。